package com.along.fastexcel.controller;

import cn.idev.excel.FastExcel;
import com.along.fastexcel.listener.BaseExcelListener;
import com.along.fastexcel.entity.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*
 * @Author: liujinyi
 * @DateTime: 2025/1/15 9:46
 */
@RestController
@RequestMapping(("/fastExcel"))
public class FastExcelController {

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("test", "UTF-8").replace("+", "%20"); // 替换加号以避免某些浏览器的解析问题
        response.setHeader("Content-disposition", "attachment; filename*=utf-8''" + fileName + ".xlsx");

        // 写入数据
        FastExcel.write(response.getOutputStream(), User.class)
                .sheet("模板")
                .doWrite(buildData());
    }

    // 创建测试数据
    private List<User> buildData() {
        // 使用 Arrays.asList() 创建包含初始化 User 对象的不可变列表
        List<User> users = Arrays.asList(
                new User().setId(1).setName("张三").setAge(18),
                new User().setId(2).setName("李四").setAge(19)
        );

        // 由于 Arrays.asList() 返回的是固定大小的列表，如果需要可变列表，可以转换为 ArrayList
        return new ArrayList<>(users);
    }


    // Excel读取功能
    @PostMapping("/upload")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择一个文件上传！");
        }
        try {
            BaseExcelListener<User> baseExcelListener = new BaseExcelListener<>();
            FastExcel.read(file.getInputStream(), User.class,
                    baseExcelListener).sheet().doRead();
            // 得到读取数据
            List<User> dataList = baseExcelListener.getDataList();
            System.out.println(dataList);
            return ResponseEntity.ok("文件上传并处理成功！");
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件处理失败！");
        }
    }

}
